/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "Ucop/System/Thread_WIN32.h"
#include <cassert>
#include "Ucop/Macros.h"
#include "Ucop/System/Runnable.h"


namespace Ucop {
namespace System {

    ThreadImpl::ThreadImpl(Runnable *_Runnable)
        : _Myid(0)
        , _Myhandle(-1L)
        , _Myrunnable(_Runnable)
    {

    }

    ThreadImpl::~ThreadImpl(void)
    {
        /* Close thread handle */
        if (_Myhandle != -1L) {
            CloseHandle((HANDLE)_Myhandle);
        }
    }

    bool ThreadImpl::StartImpl(void)
    {
        UCOP_ASSERT(_Myhandle == -1L);
        _Myhandle = _beginthreadex(NULL, 0, ThreadImpl::_Proc,
            this, 0, (unsigned int*)&_Myid);
        return _Myhandle != -1L;
    }

    void ThreadImpl::JoinImpl(void)
    {
        UCOP_ASSERT(_Myhandle != -1L);
        if (_Myhandle != -1L) {
            WaitForSingleObject(HANDLE(_Myhandle), INFINITE);
        }
    }

    bool ThreadImpl::JoinableImpl(void)
    {
        return _Myhandle != -1L;
    }

    bool ThreadImpl::SetPriorityImpl(int _Priority)
    {
        return SetThreadPriority((HANDLE)_Myhandle, _Priority) != FALSE;
    }

    ThreadImpl::ID ThreadImpl::GetCurrentIDImpl(void)
    {
        return GetCurrentThreadId();
    }

    void ThreadImpl::SleepImpl(long _Miliseconds)
    {
        Sleep((DWORD)_Miliseconds);
    }

    unsigned int ThreadImpl::_Proc(void* arg)
    {
        UCOP_ASSERT(arg != NULL);
        ThreadImpl* pth = static_cast<ThreadImpl*>(arg);
        pth->_Myrunnable->Run();
        return 0;
    }

}}